﻿@using ComputerLock.Platforms
@using ComputerLock.Resources
@using JiuLing.AutoUpgrade.Shared
@using JiuLing.AutoUpgrade.Shell
@using JiuLing.CommonLibs.ExtensionMethods
@using ComputerLock.Enums
@using System.Globalization
@using ComputerLock.Hooks
@using Microsoft.Extensions.Localization
@using System.IO
@using System.Diagnostics

@inject AppSettings AppSettings
@inject AppSettingWriter AppSettingWriter
@inject IStringLocalizer<Lang> Lang
@inject AutostartHook AutostartHook
@inject ISnackbar Snackbar
@inject UpdateHelper UpdateHelper
@inject IWindowTitleBar WindowTitleBar
@inject IDialogService DialogService

<MudDrawer @bind-Open="@_isOpen"
           Class="pa-6"
           Anchor="Anchor.End"
           Elevation="1"
           Width="350px"
           Variant="@DrawerVariant.Temporary">
    <MudDrawerContainer>

        <MudSwitch Checked="@(_isAutostart)"
                   T="bool"
                   CheckedChanged="AutostartChange"
                   Label="@(Lang["Autostart"])"
                   Color="Color.Primary" />

        <MudSwitch @bind-Checked="@(AppSettings.IsHideWindowWhenLaunch)"
                   @bind-Checked:after="SaveSettings"
                   Label="@(Lang["HideWindowWhenLaunch"])"
                   Color="Color.Primary" />
        <MudSwitch @bind-Checked="@(AppSettings.IsHideWindowWhenClose)"
                   @bind-Checked:after="SaveSettings"
                   Label="@(Lang["HideWindowWhenClose"])"
                   Color="Color.Primary" />
        <MudSwitch @bind-Checked="@(AppSettings.IsAutoCheckUpdate)"
                   @bind-Checked:after="SaveSettings"
                   Label="@(Lang["AutoCheckUpdate"])"
                   Color="Color.Primary" />

        <MudSelect Class="mt-3"
                   T="string"
                   Label="语言 Lang"
                   Value="@(AppSettings.Lang.ToString())"
                   ValueChanged="LangValueChanged">
            <MudSelectItem Value="@("zh")">中文</MudSelectItem>
            <MudSelectItem Value="@("en")">en</MudSelectItem>
        </MudSelect>

        <div class="mt-10 d-flex align-center">
            <MudChip Label="true"
                     Disabled="true"
                     Size="Size.Small">
                @(Lang["LogFiles"])
            </MudChip>

            @if (!_logLoadingOk)
            {
                <MudProgressCircular Color="Color.Primary"
                                     Class="ml-2"
                                     Size="Size.Small"
                                     Indeterminate="true" />
            }
            else
            {
                <MudChip Label="true"
                         Disabled="true"
                         Size="Size.Small">
                    @($"{_logFilesSize / 1024 / 1024:N2} MB")
                </MudChip>

                <MudButton Variant="Variant.Text"
                           Color="Color.Primary"
                           Size="Size.Small"
                           OnClick="OpenLogPath">@(Lang["OpenLogs"])</MudButton>
                <MudButton Variant="Variant.Text"
                           Color="Color.Primary"
                           Size="Size.Small"
                           OnClick="ClearLogAsync">@(Lang["RemoveLogs"])</MudButton>
            }
        </div>
        <div class="mt-4 d-flex align-center">
            <MudChip Label="true"
                     Disabled="true"
                     Size="Size.Small">
                @(_version)
            </MudChip>
            <MudButton Variant="Variant.Text"
                       Color="Color.Primary"
                       Size="Size.Small"
                       OnClick="CheckUpdateAsync">@(Lang["CheckUpdate"])</MudButton>
            <MudButton Href="@(Resource.GitHubUrl)"
                       Target="_blank"
                       Variant="Variant.Text"
                       Size="Size.Small"
                       EndIcon="@Icons.Custom.Brands.GitHub"
                       Color="Color.Primary">
                GitHub
            </MudButton>
        </div>

    </MudDrawerContainer>
</MudDrawer>

@code {
    private bool _isOpen;
    private bool _isAutostart;
    private string _version;
    private string _logPath = System.IO.Path.Combine(Environment.CurrentDirectory, "log");
    private bool _logLoadingOk = false;
    private double _logFilesSize = 0;
    protected override async Task OnInitializedAsync()
    {
        await base.OnInitializedAsync();
        _isAutostart = AutostartHook.IsAutostart();
        _version = AppBase.Version;
        _version = $"v{_version.Substring(0, _version.LastIndexOf("."))}";
    }

    public async Task OpenAsync()
    {
        _isOpen = true;
        await CalcLogSizeAsync();
    }

    private async Task CalcLogSizeAsync()
    {
        try
        {
            _logFilesSize = 0;
            _logLoadingOk = false;
            await InvokeAsync(StateHasChanged);

            if (!System.IO.Directory.Exists(_logPath))
            {
                return;
            }
            var files = Directory.GetFiles(_logPath);
            foreach (var file in files)
            {
                var fi = new FileInfo(file);
                _logFilesSize += fi.Length;
            }
        }
        catch (Exception)
        {
        }
        finally
        {
            _logLoadingOk = true;
            await InvokeAsync(StateHasChanged);
        }
    }

    private void OpenLogPath()
    {
        Process.Start("explorer.exe", _logPath);
    }

    private async Task ClearLogAsync()
    {
        bool? result = await DialogService.ShowMessageBox(
            Lang["Warning"],
            Lang["RemoveLogsConfirm"],
            yesText: Lang["Delete"],
            cancelText: Lang["Cancel"]);
        if (result != true)
        {
            return;
        }

        try
        {
            if (!System.IO.Directory.Exists(_logPath))
            {
                return;
            }
            var files = Directory.GetFiles(_logPath);
            foreach (var file in files)
            {
                File.Delete(file);
            }
        }
        catch (Exception)
        {
        }
        finally
        {
            Snackbar.Add(Lang["RemoveLogsOk"], Severity.Success);
            await CalcLogSizeAsync();
        }
    }

    private void AutostartChange(bool isChecked)
    {
        if (isChecked)
        {
            AutostartHook.EnabledAutostart();
        }
        else
        {
            AutostartHook.DisabledAutostart();
        }
        _isAutostart = AutostartHook.IsAutostart();
    }

    private void SaveSettings()
    {
        AppSettingWriter.Save(AppSettings);
    }

    private async Task CheckUpdateAsync()
    {
        await UpdateHelper.DoAsync(false);
    }

    private async Task LangValueChanged(string lang)
    {
        LangEnum langEnum = (LangEnum)Enum.Parse(typeof(LangEnum), lang);
        AppSettings.Lang = langEnum;
        SaveSettings();
        RestartTips();
    }

    private void RestartTips()
    {
        Snackbar.Configuration.NewestOnTop = true;
        Snackbar.Configuration.VisibleStateDuration = int.MaxValue;
        Snackbar.Configuration.ShowCloseIcon = true;
        Snackbar.Configuration.SnackbarVariant = Variant.Text;
        Snackbar.Add("重启后生效 Take effect after restart", Severity.Normal, config =>
        {
            config.Action = "重启 Restart";
            config.HideIcon = true;
            config.ActionColor = Color.Warning;
            config.ActionVariant = Variant.Outlined;
            config.Onclick = snackbar =>
            {
                Restart();
                return Task.CompletedTask;
            };
        });
    }

    private void Restart()
    {
        WindowTitleBar.Restart();
    }
}
